package com.maya.medicalwastes;

import android.content.Intent;
import android.inputmethodservice.ExtractEditText;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

import androidx.appcompat.app.AppCompatActivity;

import com.maya.medicalwastes.dialog.SimpleDialog;
import com.maya.medicalwastes.entity.AuthOrgEntity;
import com.maya.medicalwastes.entity.MenuEntity;
import com.maya.medicalwastes.entity.UserEntity;
import com.maya.medicalwastes.httpNet.ApiService;
import com.maya.medicalwastes.httpNet.HttpService;
import com.maya.medicalwastes.httpNet.callback.ResponseCallBack;
import com.maya.medicalwastes.httpNet.common.SharedPreferencesConstant;
import com.maya.medicalwastes.httpNet.manage.RetrofitManager;
import com.maya.medicalwastes.httpNet.model.ResultListNoPageModel;
import com.maya.medicalwastes.httpNet.model.ResultMainHomeModel;
import com.maya.medicalwastes.httpNet.model.ResultModel;
import com.maya.medicalwastes.httpNet.util.SharePreferenceOperation;
import com.maya.medicalwastes.util.FormatUtils;
import com.maya.medicalwastes.util.MyUtils;
import com.maya.medicalwastes.util.PrefUtils;
import com.maya.medicalwastes.util.StringUtils;
import com.maya.medicalwastes.util.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;


/**
 * @description 登录界面
 * @user gzl
 * @date 2017/4/25
 * @time 19:14
 */

public class LoginActivity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener {
    @BindView(R.id.edt_user)
    CleanableEditText edtUser;
    @BindView(R.id.edt_pwd)
    CleanableEditText edtPwd;
    @BindView(R.id.btn_login)
    Button btnAction;
    @BindView(R.id.view_spinner)
    Spinner viewSpinner;
    //    @BindView(R.id.tv_version_data)
//    TextView tvVersionData;
//    @BindView(R.id.logo_login)
//    ImageView logoLogin;
    @BindView(R.id.edt_scan)
    ExtractEditText edtScan;
    /**
     * 机构列表
     */
    private ArrayList<AuthOrgEntity> orgList = new ArrayList<>();
    /**
     * 机构列表
     */
    private ArrayList<String> orgMyList = new ArrayList<>();
    /**
     * spinner的适配器
     */
    private AuthOrgAdapter spinnerAdapter;
    /**
     * 机构列表无数据时第一个显示的选项
     */
    private AuthOrgEntity defaultFirstEntity;
    /**
     * 融云的token
     */
    private String token;

    //静默模式密码
    private String mQuietPassword = "maya123";
    private SimpleDialog simpleDialog;

    private boolean showOrgList = true;//是否显示选择机构列表

    private String appName;

private String scanCode;
    /**
     * 更新显示列表
     */
    public void updateOrgList() {
        orgMyList.clear();
        for (int i = 0; i < orgList.size(); i++) {
            orgMyList.add(FormatUtils.getObject(orgList.get(i).getOrgName()));
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        defaultFirstEntity = new AuthOrgEntity();
        defaultFirstEntity.setOrgName("暂无机构可选");
        defaultFirstEntity.setEnable(false);
        defaultFirstEntity.setId("-1");
        orgList.add(defaultFirstEntity);
        updateOrgList();
        SharePreferenceOperation.clearUserAllInformation(this);
        setUpView();
        // initDebugAddress();
//        Bundle bundle = getIntent().getExtras();
//        if (bundle != null) {
//            boolean isAutoLogin = bundle.getBoolean("isAutoLogin", false);
//            if (isAutoLogin) {
//                autoLogin();
//            }
//        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("111",PrefUtils.getBoolean(LoginActivity.this, SharedPreferencesConstant.IS_LOGIN, false)+"");
        Log.e("111111+++++++",PrefUtils.getString(LoginActivity.this, SharedPreferencesConstant.TOKEN, " ")+"");

        if (PrefUtils.getBoolean(LoginActivity.this, SharedPreferencesConstant.IS_LOGIN, false) && !StringUtils.isEmpty(PrefUtils.getString(LoginActivity.this, SharedPreferencesConstant.TOKEN, ""))) {
            autoLogin();
        }
    }

    private void autoLogin() {
        //  showDialog();
        HashMap<String, String> params;
        params = new HashMap<>();
        params.put("account", PrefUtils.getString(LoginActivity.this, SharedPreferencesConstant.USER_NAME, ""));
        params.put("password", PrefUtils.getString(LoginActivity.this, SharedPreferencesConstant.PASSWORD, ""));
        params.put("authOrgId", PrefUtils.getString(LoginActivity.this, "authOrgId", ""));
        Observable<ResultModel<String>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).loginCall(params);
        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultModel<String>>() {
            @Override
            public void onResponse(ResultModel<String> response) {
                //  closeDialog();
                if (response != null && response.httpCode == 200) {
                    if (!StringUtils.isEmpty(response.data)) {
                        PrefUtils.putString(LoginActivity.this, SharedPreferencesConstant.TOKEN, response.data);
                        initBaseInfo(1);//初始化orgId等 完成后再登录
                    } else {
                        ToastUtils.ViewToast(LoginActivity.this, "登录失败");
                    }
                }
            }

            @Override
            public void onFailure(int httpCode) {
                //   closeDialog();
            }
        }, LoginActivity.this);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    public void setUpView() {
        btnAction.setOnClickListener(this);
        btnAction.setOnLongClickListener(this);
        // logoLogin.setOnLongClickListener(this);
        edtUser.addTextChangedListener(textWatcher);
        edtScan.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().contains("=")) {
                    scanCode=  editable.toString().trim();
                    scanlogin(editable.toString());

                }
            }
        });
        spinnerAdapter = new AuthOrgAdapter(LoginActivity.this, R.layout.view_spinner, orgMyList);
        viewSpinner.setAdapter(spinnerAdapter);
        viewSpinner.setOnItemSelectedListener(onItemSelectedListener);
        viewSpinner.setSelection(0);
        // checkUserNameChange();
    }


    /**
     * @description 检查登录信息是否正确
     * @author gzl
     * @time 2017/4/25 19:16
     */
    public void checkLogin() {
        if (StringUtils.isEmpty(edtUser.getText().toString())) {
            ToastUtils.ViewToast(LoginActivity.this, "请输入用户名");
            return;
        }
        if (StringUtils.isEmpty(edtPwd.getText().toString())) {
            ToastUtils.ViewToast(LoginActivity.this, "请输入密码");
            return;
        }
//        if (viewSpinner.getSelectedItemPosition() == -1 || orgList.get(viewSpinner.getSelectedItemPosition()).getId().equals("-1")) {
//            ToastUtils.ViewToast(LoginActivity.this, "请选择科室或机构");
//            return;
//        }
        login();
    }

    /**
     * @description 登录
     * @author gzl
     * @time 2017/4/25 19:20
     */
    public void login() {
        // showDialog();
        HashMap<String, String> params;
        params = new HashMap<>();
        params.put("account", edtUser.getText().toString());
        params.put("password", edtPwd.getText().toString());
        params.put("authOrgId", "1320954237911351296");
        Observable<ResultModel<String>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).loginCall(params);
        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultModel<String>>() {
            @Override
            public void onResponse(ResultModel<String> response) {
                //   closeDialog();
                if (response != null && response.httpCode == 200) {
                    if (!StringUtils.isEmpty(response.data)) {
                        PrefUtils.putString(LoginActivity.this, SharedPreferencesConstant.TOKEN, response.data);
                        initBaseInfo(1);//初始化orgId等 完成后再登录
                    } else {
                        ToastUtils.ViewToast(LoginActivity.this, "登录失败");
                    }
                }
            }

            @Override
            public void onFailure(int httpCode) {
                //   closeDialog();
            }
        }, LoginActivity.this);
    }

    public void scanlogin(String code) {
        // showDialog();
        HashMap<String, String> params;
        params = new HashMap<>();
        params.put("codeInformation", code);
        Observable<ResultModel<String>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).login(params);
        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultModel<String>>() {
            @Override
            public void onResponse(ResultModel<String> response) {
                //   closeDialog();
                if (response != null && response.httpCode == 200) {
                    if (!StringUtils.isEmpty(response.data)) {
                        PrefUtils.putString(LoginActivity.this, SharedPreferencesConstant.TOKEN, response.data);
                        initBaseInfo(2);//初始化orgId等 完成后再登录
                        edtScan.setText("");
                    } else {
                        ToastUtils.ViewToast(LoginActivity.this, "登录失败");
                        edtScan.setText("");
                    }
                }
            }

            @Override
            public void onFailure(int httpCode) {
                edtScan.setText("");
                //   closeDialog();
            }
        }, LoginActivity.this);
    }

    private void initBaseInfo(int i) {
        //showDialog();
        HashMap<String, Object> param = new HashMap<>();
        param.put("menuType", MenuType.FormMobile.getType());
        param.put(ParamConstant.TOKEN, PrefUtils.getString(this, SharedPreferencesConstant.TOKEN, ""));
        Observable<ResultMainHomeModel<UserEntity, MenuEntity, AuthOrgEntity>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).getMenuListCall(param);
        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultMainHomeModel<UserEntity, MenuEntity, AuthOrgEntity>>() {
            @Override
            public void onResponse(ResultMainHomeModel<UserEntity, MenuEntity, AuthOrgEntity> response) {
                //  closeDialog();
                if (response != null && response.httpCode == 200) {

                    loginSuccess( i);//登录成功

                } else {
                    //未登录401
                    ToastUtils.ViewToast(LoginActivity.this, response.msg);
                }
            }

            @Override
            public void onFailure(int httpCode) {
                //  closeDialog();
            }
        }, LoginActivity.this);
    }


    /**
     * @description监听判断用户名的输入
     * @author gzl
     * @time 2017/7/31 14:26
     */
    public void checkUserNameChange() {
        if (!StringUtils.isEmpty(edtUser.getText().toString())) {
            // getOrgList();
        } else {
            orgList.clear();
            orgList.add(defaultFirstEntity);
            updateOrgList();
            spinnerAdapter.notifyDataSetChanged();
            viewSpinner.setSelection(0);
        }

    }

    /**
     * @description 获取机构列表
     * @author gzl
     * @time 2017/4/25 19:20
     */
    public void getOrgList() {
        Observable<ResultListNoPageModel<AuthOrgEntity>> call = RetrofitManager.getInstance().getRetrofit().create(ApiService.class).getOrgListCall(edtUser.getText().toString());
        HttpService.getInstance().enqueue(call, new ResponseCallBack<ResultListNoPageModel<AuthOrgEntity>>() {

            @Override
            public void onResponse(ResultListNoPageModel<AuthOrgEntity> response) {
                if (response != null && response.httpCode == 200) {
                    orgList.clear();
                    orgMyList.clear();
                    if (response.data != null) {
                        orgList.addAll(response.data);
                    }
                    if (orgList.size() <= 0) {
                        orgList.add(defaultFirstEntity);
                    }
                    updateOrgList();
                    viewSpinner.setSelection(0);
                    spinnerAdapter.notifyDataSetChanged();
                } else {
                    orgList.clear();
                    orgList.add(defaultFirstEntity);
                    updateOrgList();
                    spinnerAdapter.notifyDataSetChanged();
                    viewSpinner.setSelection(0);
                }
            }

            @Override
            public void onFailure(int httpCode) {
                orgList.clear();
                orgList.add(defaultFirstEntity);
                updateOrgList();
                spinnerAdapter.notifyDataSetChanged();
                viewSpinner.setSelection(0);
            }
        }, LoginActivity.this);
    }

    /**
     * @description 登陆成功
     * @author gzl
     * @time 2017/4/26 10:24
     * @param i
     */
    public void loginSuccess(int i) {
        PrefUtils.putBoolean(LoginActivity.this, SharedPreferencesConstant.IS_LOGIN, true);
        PrefUtils.putString(LoginActivity.this, SharedPreferencesConstant.USER_NAME, edtUser.getText().toString());
        PrefUtils.putString(LoginActivity.this, SharedPreferencesConstant.PASSWORD, edtPwd.getText().toString());


        Log.e("111",PrefUtils.getBoolean(LoginActivity.this, SharedPreferencesConstant.IS_LOGIN, false)+"");
        Log.e("111111+++++++",PrefUtils.getString(LoginActivity.this, SharedPreferencesConstant.TOKEN, " ")+"");


        if (i==2){
            PrefUtils.putString(LoginActivity.this, "authOrgId", scanCode.split("_")[2]);
        }else {
            PrefUtils.putString(LoginActivity.this, "authOrgId", orgList.get(viewSpinner.getSelectedItemPosition()).getId());
        }
        MyUtils.IntentToOther(LoginActivity.this, MainActivity.class, null);
        finish();
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            System.exit(0);
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * spinner的选择监听
     */
    AdapterView.OnItemSelectedListener onItemSelectedListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    };
    /**
     * 账户输入监听
     */
    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            checkUserNameChange();
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                //登录
                checkLogin();
                break;
        }
    }

    @Override
    public boolean onLongClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                //长按登录
                showVerifyDialog();
                break;
//            case R.id.logo_login:
//                showOrgList = !showOrgList;
//                if (showOrgList) {
//                    viewSpinner.setVisibility(View.VISIBLE);
//                } else {
//                    viewSpinner.setVisibility(View.GONE);
//                }
//                break;
        }
        return true;
    }

    private void showVerifyDialog() {
        simpleDialog = SimpleDialog.create(getSupportFragmentManager())
                  .setViewListener(new SimpleDialog.ViewListener() {
                      @Override
                      public void bindView(View v) {
                          initVerifyDialogView(v);
                      }
                  })
                  .setLayoutRes(R.layout.dialog_verify)
                  .setShowLocation(SimpleDialogStyle.SHOW_LOACTION_CENTER)
                  .setWidth(SimpleDialogStyle.WIDTH_WRAP_CONTENT)
                  .setDimAmount(0.5f)
                  .setTag("SimpleDialog");
        simpleDialog.show();

    }

    private void initVerifyDialogView(View v) {
        final EditText et_secret_input = v.findViewById(R.id.et_secret_input);
        Button btn_ok = v.findViewById(R.id.btn_ok);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mQuietPassword.equalsIgnoreCase(et_secret_input.getText().toString())) {
                    Intent intent = new Intent(LoginActivity.this, SettingActivity.class);
                    startActivity(intent);
                    if (simpleDialog != null) {
                        simpleDialog.dismiss();
                    }
                } else {
                    ToastUtils.ViewToast(LoginActivity.this, "密码错误！");
                }
            }
        });
    }

   /* private void initDebugAddress() {
        SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
        if (ApiConfigConstant.DEBUG_MODE) {
            String ip = sp.getString("ip", ApiConfigConstant.DEBUG_IP);
            String port = sp.getString("port", ApiConfigConstant.DEBUG_PORT);
            ApiConfigConstant.DEBUG_IP = ip;
            ApiConfigConstant.DEBUG_PORT = port;
            ApiConfigConstant.DEBUG_URL = ApiConfigConstant.HTTP + ApiConfigConstant.DEBUG_IP + ":" + ApiConfigConstant.DEBUG_PORT;
        } else {
            String ip = sp.getString("ip", ApiConfigConstant.BASE_IP);
            String port = sp.getString("port", ApiConfigConstant.BASE_PORT);
            ApiConfigConstant.BASE_IP = ip;
            ApiConfigConstant.BASE_PORT = port;
            ApiConfigConstant.BASE_URL = ApiConfigConstant.HTTP + ApiConfigConstant.BASE_IP + ":" + ApiConfigConstant.BASE_PORT;
        }

    }*/
}
